package controllers

import (
	"github.com/astaxie/beego"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	//"fmt"
	"context"
	"crypto/md5"
	"fmt"
)
type DataRespose struct{
	Code string `json:"code"`
	Total interface{} `json:"total"`
	Data interface{} `json:"data"`
}
type SingleResponse struct {
	Code string `json:"code"`
	Data interface{} `json:"data"`
}
type CustomResponse struct {
	Code string `json:"code"`
	Data []interface{} `json:"data"`
}
type ExecResponse struct {
	Code string `json:"code"`
	Msg string `json:"msg"`
}
type BaseController struct{
	beego.Controller
}

func (this * BaseController) SetServerHeader(){
	if beego.BConfig.RunMode != "prod" {
		this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")       //允许访问源
		this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "*")    //允许post访问
		this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
		this.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
		this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
		this.Ctx.ResponseWriter.Header().Set("Content-type", "application/json") //返回数据格式是json
	}
}
func (this * BaseController) Serve(data interface{}){
	this.SetServerHeader()
	cb := this.GetString("callback")
	if cb != "" {
		this.Data["jsonp"] = data
		this.ServeJSONP()
	}else{
		this.Data["json"] = data
		this.ServeJSON()
	}
}
func (this * BaseController)Response(data interface{},total interface{})  {
	this.Serve(&DataRespose{
		Code:"ok",
		Total:total,
		Data:data})
}
//func (this * BaseController)ResponseCustom(data [] orm.Params,total interface{})  {
//	this.Serve(&DataRespose{
//		Code:"ok",
//		Total:total,
//		Data:data})
//}
func (this * BaseController)Single(data interface{})  {
	this.Serve(&SingleResponse{
		Code:"ok",
		Data:data})
}
func (this * BaseController)CustomRow(data []interface{})  {
	this.Serve(&CustomResponse{
		Code:"ok",
		Data:data})
}
func (this * BaseController)Fail(msg string,fail string)  {
	if fail == "" {
		fail = "fail"
	}
	//this.Data["jsonp"] = &FailResponse{
	//	Code:fail,
	//	Msg:msg}
	//this.ServeJSONP()
	this.Serve(&ExecResponse{
		Code:fail,
		Msg:msg})
}

func (this * BaseController)Success(msg string)  {
	this.Serve(&ExecResponse{
		Code:"ok",
		Msg:msg})
}

func (this *BaseController) Upload(){
	qiniu_ak := "YICBiD6x7yX_UfxlzWrU3x0UuCLmWC-L_1rt86su"
	qiniu_sk := "Pn1NBs8-Ev-y2OhGNP30GPtmUnP0yYeWRHce7-Cc"
	bucket := "pqtest"
	f, h, _ := this.GetFile("file")
	mime := h.Header.Get("Content-Type")
	ext := "jpg"
	switch string(mime[0]) {
	case "image/png": ext = "png"
	case "image/gif": ext = "gif"
	}
	data := []byte(h.Filename)
	filename := fmt.Sprintf("%x", md5.Sum(data))
	path := "/tmp/"+filename+"."+ext
	defer f.Close()
	this.SaveToFile("file",path)
	localFile := path
	key := filename+"."+ext
	putPolicy := storage.PutPolicy{
		Scope:               bucket,
	}
	mac := qbox.NewMac(qiniu_ak, qiniu_sk)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "avatar logo",
		},
	}
	err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, &putExtra)
	if err != nil {
		//fmt.Println(err)
		beego.Warning(err)
		//return
	}
	//beego.Debug(ret.Key,ret.Hash)
	//删除本地文件
	//os.Remove(path)
	this.Success(filename+"."+ext)
}